﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Duellum.Core;
using Duellum.Wpf2d.Plugin;
using IEnumerable = System.Collections.IEnumerable;

namespace Duellum.Wpf.Edit
{
	/// <summary>
	/// Interaction logic for EditorToolbar.xaml
	/// </summary>
	public partial class EditorToolbox : UserControl
	{
		IEnumerable source;
		
		public EditorToolbox()
		{
			InitializeComponent();
		}
		
		public void LoadButtons()
		{
			var domain = App.Current.CurrentDomain;
			var wpf2d = domain.GetPlugin<Wpf2dPlugin>(); //Wpf2dPlugin.Current;
			
			const double zoom = 1;
			
			var types
				= domain.GetTypes()
				.Where(t => t.IsConcrete)
				.OrderBy(t => EditorPlugin.GetUIOrder(t))
				.ThenByDescending(t => t.Id.ToString());
			
			source = types
				.Select(t => new Image() {
					Source = wpf2d.GetImage(t) ?? wpf2d.GetHexBorderImg(zoom),
					ToolTip = new ToolTip() { Content = t.Id.ToString() },
					Tag = t
				}).ToArray();
			toolbarList.Items.Clear();
			toolbarList.ItemsSource = source;
			SelectFisrt();
			toolbarList.SelectionChanged += toolbarList_SelectionChanged;
		}

		void toolbarList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (toolbarList.SelectedItem == null) {
				var item = e.RemovedItems.OfType<FrameworkElement>().FirstOrDefault();
				if (item != null) {
					//toolbarList.SelectedItem = item; //<- this does not keep the button to appear unchecked
					var itemContainer = toolbarList.ContainerFromElement(item);
					var btn = (ToggleButton)VisualTreeHelper.GetChild(itemContainer, 0);
					btn.IsChecked = true;
				} else {
					SelectFisrt(); //this is unlikely to happen
				}
			}
		}
		
		public void SelectFisrt()
		{
			if (toolbarList.HasItems) toolbarList.SelectedIndex = 0;
		}
		
		public DuelType Selected
		{
			get {
				if (toolbarList.SelectedItem == null) return null;
				
				return (DuelType)((FrameworkElement)toolbarList.SelectedItem).Tag;
			}
		}
	}
}
